import React, { useMemo, useEffect, useState } from 'react';
import s from './style.module.css';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import Table from '@knownsec/react-component/dist/Table';
import EmptyData from '../../../../../components/empty/EmptyData';

import Pagination from '@knownsec/react-component/dist/Pagination';
import cn from 'classnames';
import { Link } from 'react-router-dom';
import Button from '@knownsec/react-component/dist/Button';
import Input from '@kuiper-components/input';
import Icon from '@knownsec/react-component/dist/Icon';
import fetchFer from 'API/fetch';
import Select, { Option } from '@kuiper-components/select';
import { Search24 as SearchIcon } from '@carbon/icons-react';
import { WARNING_CATEGORY_KEY_LABEL_MAP } from '../../../../../../common/constants';
import moment from 'moment';
import { turnToUrlparam } from '../../../../../helpers/getUrlParams';
import IgnoreRiskConfirm from '../../../../../components/IgnoreRiskDialog';

import { cloneDeep } from 'lodash';
const optionData = [
	{ label: '严重', value: '5' },
	{ label: '高危', value: '4' },
	{ label: '中危', value: '3' },
	{ label: '低危', value: '2' },
];
const defaultFilter = {
	page: 1,
	limit: 10,
};
const levelColor = {
	5: '#D5342F',
	4: '#F04038',
	3: '#F18246',
	2: '#FCD94A'
}
const colorMap = {
	严重: { color: '#A00000' },
	高危: { color: '#E01010' },
	中危: { color: '#F5A623' },
	低危: { color: '#F8E71C' },
	未知: { color: '#9B9B9B' },
	安全: { color: '#11AB4E' },
};
let setT = null;
function Detail({
	match: {
		params: { assetType, jid },
	},
	tid,
	atid,
	checked,
	jobId,
	target,
	taskType,
	isHistory,
	targetUrl = '',
	isSchedule,
	targetStatusTableTip,
	enableTaskType,
	changeOverview
}) {
	const resD = JSON.parse(sessionStorage.resD).feature;
	const [filter, setFilter] = React.useState(defaultFilter);
	const [data, setData] = React.useState([]);
	const [tableData, setTableData] = React.useState({
		data: [],
		total: 0,
	});
	const [tableLoading, setTableLoading] = React.useState(false);
	const [refresh, setRefresh] = useState(false)

	const colum = [
		{
			title: '风险地址',
			dataIndex: 'affects',
			key: 'affects',
		},
		{
			title: '威胁名称',
			dataIndex: 'title',
			key: 'title',
		},
		{
			title: '威胁类型',
			dataIndex: 'category',
			key: 'category',
			render(e) {
				return WARNING_CATEGORY_KEY_LABEL_MAP.ssl[e];
			},
		},
		{
			title: '威胁等级',
			dataIndex: 'level',
			key: 'level',
			render(e) {
				const levelName = optionData.filter(item => {
					return +item.value === +e;
				})[0].label;
				return <span style={{ color: levelColor[e] }}>{levelName}</span>;
			},
		},
		{
			title: '操作',
			dataIndex: 'name',
			key: 'name',
			render(e, row) {
				return (
					<><Link
						className={s.item}
						to={{
							pathname: '/asset-manage/manage/web/ssl-detail',
							state: {
								category: row.category,
								taskId: row.task_id,
								warningId: row._id,
							},
						}}
					>
						查看详情
					</Link>
					<IgnoreRiskConfirm className={'ml5'} data={{ task_id: row.task_id, warning_ids: [row._id] }} refresh={() => setRefresh(true)} />
				</>
				);
			},
		},
	];
	const getDetailNew = async () => {
		if (!tid) return false
		setTableLoading(true);
		const sendData1 = {
			task_id: tid,
		};
		const params1 = turnToUrlparam(sendData1);
		const res2 = await fetchFer(
			`/api/v2/tasks/web_security/type/detail?${params1}`,
			{
				method: 'GET',
				checkStatus: 501,
			}
		);
		if (res2.code === 200) {
			setData(res2.data);
		}
		setTableLoading(false);
	};
	const getData = () => {
		const totalData = data?.warnings?.reduce((total, item) => {
			let i = cloneDeep(item);
			i.task_id = data.task_id;
			i.key = i._id
			if (i.level.toString() === '1') i.level = 2;
			if (filter.affects && item.affects.indexOf(filter.affects) === -1) {
				i = null;
			}
			if (filter.title && item.title.indexOf(filter.title) === -1) {
				i = null;
			}
			if (filter.level && item.level.toString() !== filter.level) {
				i = null;
			}
			if (filter.category && item.category !== filter.category) {
				i = null;
			}
			if (i) total.push(i);
			return total;
		}, []);
		const resultList = [];
		const limit = filter.limit || 10;
		if (totalData?.length > 0) {
			Array(Math.ceil(totalData.length / limit))
				.fill('')
				.map((i, k) => {
					resultList.push(totalData.slice(k * limit, k * limit + limit));
				});
		}
		setTableData({
			data: resultList,
			total: totalData?.length || 0,
		});
		setRefresh(false)
	};
	const [selectedRows, setSelectedRows] = useState([])
	const onSelectAll = (selected, sr, changeRows) => {
		const changeKeys = changeRows.map(i => i._id)
		if (!selected) {
			setSelectedRows(selectedRows.filter(i => !changeKeys.includes(i)))
		} else {
			setSelectedRows(Array.from(new Set(selectedRows.concat(changeKeys))))
		}
	}
	const onSelect = (r, selected, ss, n) => {
		if (!selected) {
			setSelectedRows(selectedRows.filter(i => i !== r._id))
		} else {
			setSelectedRows(Array.from(new Set(selectedRows.concat([r._id]))))
		}
	}
	const handleChangeSearch = e => {
		e && setFilter({ ...filter, ...e });
	};
	const checkData = () => {
		let text = '暂无数据';
		let img = 'noData';
		if (!tid) {
			if (!resD.sslTask && !resD.sslManualTask) {
				text = '当前套餐不支持该监测项，请先升级套餐。';
				img = 'noPrmission';
			} else if (targetUrl.split('//')[0] === 'http:') {
				text = '当前资产为HTTP协议，不支持SSL安全监测。';
			} else if (checked === 0) {
				text = (
					<span>
						该资产未启用该监测项，您可前往“任务管理 -
						<Link
							to={{
								pathname: '/job-manage/create-job-all',
								search: `assetType=web&jid=${jobId}&isSchedule=${isSchedule}`,
							}}
						>
							Web安全监测
						</Link>
						”下发监测任务。
					</span>
				);
				img = 'dataLoading';
			} else if (tid === false) {
				text = '任务数据已过期，您可重新下发监测任务'
			}
		} else {
			return targetStatusTableTip(data, 'SSL安全')
		}
		return { img, text };
	};
	useEffect(() => {
		getDetailNew();
	}, [tid]);
	useEffect(() => {
		getData();
	}, [filter, data]);
	useEffect(() => {
		if (refresh) {
			changeOverview(true)
			getDetailNew()
		}
	}, [refresh])

	return (
		<div className={s.tableMain}>
			<div className={cn(s.flex, s.aic)}>
			最近更新时间：
				<span className={cn(s.pl10, s.pr20)}>
					{Object.keys(data).length > 0
						? moment(data?.time_info?.end_time).format('YYYY-MM-DD HH:mm:ss')
						: '- -'}
				</span>
				{/* <Link
					to={{
						pathname: '/job-manage/web-task',
						search: `filter=${encodeURI(
							JSON.stringify({ target_url: target })
						)}`,
					}}
				>
					查看任务
				</Link> */}
			</div>
			<div className={s.search}>
				<div>
					<Input
						onChange={affects => {
							setFilter({ ...filter, affects });
						}}
						className={cn(s.input, s.mr10)}
						placeholder="搜索风险地址"
						after={
							<SearchIcon
								className={s.icon}
								onClick={() => {
									handleChangeSearch();
								}}
							/>
						}
						value={filter.affects}
						onPressEnter={() => {
							handleChangeSearch();
						}}
						type="search"
					/>
					<Input
						onChange={title => {
							setFilter({ ...filter, title });
						}}
						className={s.input}
						placeholder="搜索漏洞名称"
						after={
							<SearchIcon
								className={s.icon}
								onClick={() => {
									handleChangeSearch();
								}}
							/>
						}
						value={filter.title}
						onPressEnter={() => {
							handleChangeSearch();
						}}
						type="search"
					/>
				</div>

				<div className={s.selectContainer}>
					<Select
						placeholder="威胁等级"
						className={s.item}
						value={filter.level}
						allowClear={true}
						getPopupContainer={triggerNode => triggerNode}
						onChange={level => {
							handleChangeSearch({ level });
						}}
					>
						{optionData.map(e => (
							<Option key={e.value} value={e.value}>
								{e.label}
							</Option>
						))}
					</Select>
					<Select
						placeholder="威胁类型"
						className={s.item}
						value={filter.category}
						allowClear={true}
						getPopupContainer={triggerNode => triggerNode}
						onChange={category => {
							handleChangeSearch({ category });
						}}
					>
						{Object.keys(WARNING_CATEGORY_KEY_LABEL_MAP.ssl).map(e => (
							<Option key={e} value={e}>
								{WARNING_CATEGORY_KEY_LABEL_MAP.ssl[e]}
							</Option>
						))}
					</Select>
					<Button
						className={'primary-btn'}
						onClick={() => {
							setFilter(defaultFilter);
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<Table
				loading={tableLoading}
				className={s.newtable}
				pro
				columns={colum}
				data={tableData.data[filter.page - 1] || []}
				rowSelection={{
					selectedRowKeys: selectedRows,
					width: 50,
					onSelect,
					onSelectAll
				}}
				empty={
					<EmptyData
						emptyType={checkData().img}
						text={checkData().text}
						className={s.nobor}
					/>
				}
			/>
			<div>
				<div className={cn('df aic jcsb mt10')}>
					<IgnoreRiskConfirm className={'p0'}
						text='批量忽略'
						disabled={selectedRows?.length === 0}
					 	data={{ warning_ids: selectedRows, task_id: data?.task_id }} refresh={_ => {
							setRefresh(true)
							setSelectedRows([])
						}} />
					{tableData.total > 10 && (
						<Pagination
							total={tableData.total}
							current={filter.page || 1}
							pageSize={filter.limit || 10}
							pageSizeOptions={[10, 20, 50]}
							showSizeChanger
							showQuickJumper
							showTotal={total => `共${total}条`}
							onChange={(page, limit) => {
								handleChangeSearch({ page, limit });
							}}
						/>
					)}
				</div>
			</div>
		</div>
	);
}
Detail.propTypes = {
	tid: PropTypes.any,
	atid: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
